import { put, takeEvery } from 'redux-saga/effects'
import {
  addProductToCart,
  addProductToLocalCart,
  changeLocalProductCount,
  changeProductCount,
  deleteCarts,
  deleteLocalCarts,
  loadCarts,
  saveCarts
} from '../actions/cart.actions'
import axios from 'axios'
function* handleAddProductToCart(action) {
  const { data } = yield axios.post('http://localhost:3005/cart/add', { gid: action.payload })
  yield put(addProductToLocalCart(data))
}

function* handleLoadCarts() {
  const { data } = yield axios.get('http://localhost:3005/cart')
  yield put(saveCarts(data))
}

function* handleDeleteCarts(action) {
  yield axios.delete('http://localhost:3005/cart/delete', {
    params: { cid: action.payload }
  })
  yield put(deleteLocalCarts(action.payload))
}

function* handleChangeProductCount(action) {
  const {data} = yield axios.put('http://localhost:3005/cart', action.payload)
  yield put(changeLocalProductCount(data))
}

export default function* cartSaga() {
  yield takeEvery(addProductToCart, handleAddProductToCart)
  yield takeEvery(loadCarts, handleLoadCarts)
  yield takeEvery(deleteCarts, handleDeleteCarts)
  yield takeEvery(changeProductCount, handleChangeProductCount)
}
